package com.nobug.service.issue;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nobug.bean.BaseRespVo;
import com.nobug.bean.brand.Brand;
import com.nobug.bean.brand.BrandExample;
import com.nobug.bean.brand.VO.BrandListVO;
import com.nobug.bean.issue.Issue;
import com.nobug.bean.issue.IssueCreateBO;
import com.nobug.bean.issue.IssueExample;
import com.nobug.bean.issue.IssueListVO;
import com.nobug.mapper.issueMapper.IssueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IssueServiceImpl implements IssueService{
    @Autowired
    IssueMapper mapper;

    @Override
    public BaseRespVo<IssueListVO> queryIssueList(Integer offset, Integer limit, String sort, String order, String question) {
        List<Issue> issues = mapper.selectListByQuestion(offset, limit, sort, order, question);
        PageInfo<Issue> brandPageInfo = new PageInfo<>(issues);
        long total = brandPageInfo.getTotal();
        /*此时排序查找已经执行，分页也完成，需要创建一个BrandListVO*/
        IssueListVO issueListVO = IssueListVO.getInstance(total, issues);
        BaseRespVo<IssueListVO> results = BaseRespVo.ok(issueListVO);
        return results;
    }

    @Override
    public BaseRespVo<IssueListVO> queryIssueList(Integer page, Integer limit, String sort, String order) {
        /*引入分页插件，来做分页, 分页插件就是给我们的sql预编译语句，添加page， 和limit， 使用分页查询，需要告诉springboot我们使用的数据库是mysql*/
        Page<Issue> objects = PageHelper.startPage(page, limit);
        IssueExample issueExample = new IssueExample();
        issueExample.setOrderByClause(sort + " " + order);
        List<Issue> issues = mapper.selectByExample(issueExample);
        /*获取分页信息，起始页，size，total等*/
        PageInfo<Issue> brandPageInfo = new PageInfo<>(issues);
        long total = brandPageInfo.getTotal();
        /*此时排序查找已经执行，分页也完成，需要创建一个BrandListVO*/
        IssueListVO issueListVO = IssueListVO.getInstance(total, issues);
        BaseRespVo<IssueListVO> results = BaseRespVo.ok(issueListVO);
        return results;
    }

    @Override
    public BaseRespVo<Issue> issueCreate(IssueCreateBO issueCreateBO) {
        Date date = new Date();
        Issue issue = new Issue(issueCreateBO.getQuestion(), issueCreateBO.getAnswer(), date, date);
        Integer lastInsertId = mapper.insertSelective(issue);
        issue = mapper.selectByPrimaryKey(lastInsertId);
        BaseRespVo<Issue> baseRespVo = BaseRespVo.ok(issue);
        return baseRespVo;
    }
}
